package api

import (
	"github.com/gin-gonic/gin"
	"web-collect-server/entity"
	"web-collect-server/entity/common/response"
	"web-collect-server/global"
)

func InitLoginRouter(r *gin.RouterGroup) {
	// 给 一个 api 的路由组
	g := r.Group("/login")
	g.POST("", login)
	g.POST("userInfo", getUserInfoByToken)
}

func getUserInfoByToken(c *gin.Context) {
	var user entity.User
	global.DB.First(&user)
	response.OkWithData(user, c)
}

func login(c *gin.Context) {
	var user entity.User
	err := c.ShouldBindJSON(&user)
	if err != nil {
		response.FailWithMessage("解析user json 失败 ", c)
		return
	}
	var users []entity.User
	results := global.DB.Where("name= ?", user.Name).Find(&users)
	if results.RowsAffected == 0 {
		response.FailWithMessage("用户不存在!", c)
		return
	}
	first := users[0]
	if first.Password != user.Password {
		response.FailWithMessage("密码不正确!", c)
		return
	}
	tokenRes := entity.LoginRes{Token: first.Name}
	response.OkWithData(tokenRes, c)
}
